
package com.xl.frontendproject;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "sessionCookieServlet", value = "/session-cookie-demo")
public class SessionCookieServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应的内容类型为 HTML，并指定字符编码为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // Session操作示例
        HttpSession session = request.getSession();
        Integer visitCount = (Integer) session.getAttribute("visitCount");
        visitCount = (visitCount == null) ? 1 : visitCount + 1;
        session.setAttribute("visitCount", visitCount);

        // Cookie操作示例
        // 创建一个 Cookie 来记录用户的最后访问时间
        Cookie visitCookie = new Cookie("lastVisit", String.valueOf(System.currentTimeMillis()));
        visitCookie.setMaxAge(3600); // 设置 Cookie 的有效期为 1 小时
        response.addCookie(visitCookie); // 将 Cookie 添加到响应中

        // 转发到展示页面
        // 将访问次数设置为请求属性，以便在 JSP 页面中显示
        request.setAttribute("sessionData", visitCount);

        try {
            // 转发请求到 session-cookie-demo.jsp 页面进行展示
            request.getRequestDispatcher("session-cookie-demo.jsp").forward(request, response);
        } catch (Exception e) {
            // 如果转发过程中出现异常，则返回 500 内部服务器错误
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }


    // 在SessionCookieServlet中添加POST处理
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession(); // 获取当前会话对象
        Integer count = (Integer) session.getAttribute("visitCount");
        session.setAttribute("visitCount", count != null ? count + 1 : 1);
        response.sendRedirect("session-cookie-demo");
    }

}

